#include <iostream>

using std::cout;
using std::endl;

class Data
{
public:
    Data(int data = 0)
    : _data(data)
    {
        cout << "Data(int  = 0)" << endl;
    }

    int getData() const
    {
        return _data;
    }

    ~Data()
    {
        cout << "~Data()" << endl;
    }
private:
    int _data;
};

class SmartPointer
{
public:
    SmartPointer(Data *pdata)
    : _data(pdata)
    {
        cout << "SmartPointer(Data *)" << endl;
    }

    //重载箭头访问运算符
    Data *operator->()
    {
        return _data;
    }

    //解引用运算符的重载
    Data &operator*()
    {
        return *_data;
    }

    ~SmartPointer()
    {
        cout << "~SmartPointer()" << endl;
        if(_data)
        {
            delete _data;
            _data = nullptr;
        }
    }
private:
    Data *_data;
};

class ThirdLayer
{
public:
    ThirdLayer(SmartPointer *psl)
    : _sl(psl)
    {
        cout << "ThirdLayer(SmartPointer *)" << endl;
    }

    SmartPointer &operator->()
    {
        return *_sl;
    }

    ~ThirdLayer()
    {
        cout << "~ThirdLayer()" << endl;
        if(_sl)
        {
            delete _sl;
            _sl = nullptr;
        }
    }
private:
    SmartPointer *_sl;
};

int main(int argc, char **argv)
{
    //pointer可以看成是智能指针
    SmartPointer pointer(new Data(10));//pointer是个栈对象
    /* pointer.operator->()->getData(); */
    cout << "pointer->getData() = " << pointer->getData() << endl;
    /* pointer.operator*().getData(); */
    cout << "(*pointer).getData() = " << (*pointer).getData() << endl;

    /* ThirdLayer tl(new SmartPointer(new Data(20))); */
    /* tl.operator->().operator->()->getData(); */
    /* cout << "tl->getData() = " << tl->getData() << endl; */

    return 0;
}

